#include"../include/receive1.h"
#include"../include/data_process.h"

char myport[10] = "8150";
int udp_fd;
struct sockaddr_in my_addr;
struct sockaddr_in dst_addr;
char recv_buf[60000];
Mat img_decode;
Mat dst_image;
int n_recv;
//string str_tmp = (*recv_buf).str();
vector<uchar> data;


//udp初始化
void init_udp()
{
    cout<<"A节点 start work！"<<endl;
    udp_fd = socket(AF_INET,SOCK_DGRAM,0);
    if(udp_fd == -1)
    {
        perror("socket failed!");
    }
}

//初始化地址，端口
void init_my_addr()
{
    bzero(&my_addr,sizeof(my_addr));
    my_addr.sin_family = AF_INET;
    my_addr.sin_port = htons(atoi(myport));
    my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
}

//绑定
void bind_udp()
{
    int opt = 1;
    setsockopt(udp_fd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
    if(bind(udp_fd,(const struct sockaddr *)&my_addr,sizeof(my_addr)))
    {
        perror("bind failed");
    }
}

//接受数据
void receive_data()
{
    //printf("Waitting data ~~~~~~\n");
    bzero(&dst_addr,sizeof(dst_addr));
    bzero(recv_buf,sizeof(recv_buf));
    socklen_t len = sizeof(dst_addr);
    n_recv = recvfrom(udp_fd,recv_buf,sizeof(recv_buf),0,(struct sockaddr *)&dst_addr,&len);
    //cout<<"ip:"<<inet_ntoa(dst_addr.sin_addr)<<" port:"<<ntohs(dst_addr.sin_port)<<" bety:"<<n_recv<<" data:"<<recv_buf<<endl;
}

//解压数据
void chage_data()
{
    for(auto i : recv_buf)
    {
        data.push_back(i);
    }
    img_decode = imdecode(data,CV_LOAD_IMAGE_COLOR);
    resize(img_decode,img_decode,Size(640,480),0,0,INTER_AREA);
    
    /*
    if(waitKey(10)==27)
        destroyAllWindows();
        break;
    */
}

//接受端初始化集成函数
void receive_init_all()
{
    init_udp();
    init_my_addr();
    bind_udp();
}

//接受端工作集成函数
void receive_do_all()
{
    while (1)
    {
        receive_data();
        chage_data();
        process(img_decode,dst_image,"A节点");
        data.clear();
    }
}